package com.example.canteen.service;

import com.example.canteen.converter.CategoryConverter;
import com.example.canteen.converter.DishConverter;
import com.example.canteen.dao.Category;
import com.example.canteen.dao.CategoryRepository;
import com.example.canteen.dao.Dish;
import com.example.canteen.dao.DishRepository;
import com.example.canteen.dto.DishDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Set;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl implements DishService {
    @Autowired
    DishRepository dishRepository;
    @Autowired
    CategoryRepository categoryRepository;

    @Override
    public Set<DishDTO> getAllDishes() {
        return dishRepository.findAll().stream().map(DishConverter::convertDish).collect(Collectors.toSet());
    }

    @Override
    public DishDTO getDishByName(String name) {
        return DishConverter.convertDish(dishRepository.findByName(name));
    }

    @Override
    public Long addDish(DishDTO dishDTO, String categoryName) {
        if (dishRepository.findByName(dishDTO.getName()) != null) {
            throw new IllegalArgumentException("Dish already exists");
        }
        dishDTO.setCategoryDTO(CategoryConverter.convertCategory(categoryRepository.findByName(categoryName)));
        return dishRepository.save(DishConverter.convertDish(dishDTO)).getId();
    }

    @Transactional
    @Override
    public void deleteDishByName(String name) {
        dishRepository.deleteByName(name);
    }


    @Override
    public DishDTO updateDish(long id, String name, String categoryName, String components ){
        Dish dishInDB = dishRepository.findById(id).orElseThrow(
                () -> new IllegalArgumentException("Dish not found")
        );
        if (StringUtils.hasLength(name) && !name.equals(dishInDB.getName()))
            dishInDB.setName(name);
        Category category = categoryRepository.findByName(categoryName);
        if (category != null && !category.equals(dishInDB.getCategory()))
            dishInDB.setCategory(category);
        if (StringUtils.hasLength(components) && !components.equals(dishInDB.getComponents()))
            dishInDB.setComponents(components);
        return DishConverter.convertDish(dishRepository.save(dishInDB));
    }
}
